/**
 * 调试工具函数
 * 用于帮助开发者诊断和解决常见问题
 */

/**
 * 测试CORS配置是否正确
 * @param {string} url - 要测试的API URL（可以是相对路径）
 * @returns {Promise<Object>} - 测试结果
 */
export const testCORS = async (url) => {
  // 如果是相对路径，转换为绝对路径
  const fullUrl = url.startsWith('http') ? url : `${window.location.origin}${url}`;
  console.log(`开始CORS测试: ${fullUrl}`);
  
  try {
    // 1. 发送OPTIONS预检请求
    const optionsResponse = await fetch(fullUrl, {
      method: 'OPTIONS',
      headers: {
        'Access-Control-Request-Method': 'POST',
        'Access-Control-Request-Headers': 'Content-Type, Authorization',
        'Origin': window.location.origin
      }
    });
    
    console.log('OPTIONS预检请求结果:', {
      status: optionsResponse.status,
      statusText: optionsResponse.statusText,
      headers: {
        'Access-Control-Allow-Origin': optionsResponse.headers.get('Access-Control-Allow-Origin'),
        'Access-Control-Allow-Methods': optionsResponse.headers.get('Access-Control-Allow-Methods'),
        'Access-Control-Allow-Headers': optionsResponse.headers.get('Access-Control-Allow-Headers'),
        'Access-Control-Allow-Credentials': optionsResponse.headers.get('Access-Control-Allow-Credentials')
      }
    });
    
    // 2. 发送简单GET请求
    const getResponse = await fetch(fullUrl, {
      method: 'GET',
      headers: {
        'Content-Type': 'application/json',
        'Origin': window.location.origin
      }
    });
    
    console.log('GET请求结果:', {
      status: getResponse.status,
      statusText: getResponse.statusText,
      headers: {
        'Access-Control-Allow-Origin': getResponse.headers.get('Access-Control-Allow-Origin')
      }
    });
    
    return {
      success: optionsResponse.ok,
      message: optionsResponse.ok ? 'CORS配置正确' : 'CORS预检请求失败',
      optionsStatus: optionsResponse.status,
      getStatus: getResponse.status
    };
  } catch (error) {
    console.error('CORS测试失败:', error);
    return {
      success: false,
      message: `CORS测试异常: ${error.message}`,
      error: error
    };
  }
};

/**
 * 检查网络连接状态
 * @param {string} url - 要测试的URL
 * @returns {Promise<Object>} - 测试结果
 */
export const checkNetworkConnection = async (url) => {
  try {
    const startTime = Date.now();
    const response = await fetch(url, { 
      method: 'HEAD',
      cache: 'no-store'
    });
    const endTime = Date.now();
    
    return {
      success: response.ok,
      latency: endTime - startTime,
      status: response.status,
      message: `连接成功，延迟: ${endTime - startTime}ms`
    };
  } catch (error) {
    return {
      success: false,
      message: `连接失败: ${error.message}`,
      error: error
    };
  }
};

export default {
  testCORS,
  checkNetworkConnection
};
